package com.zmn.uac.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.uac.api.constant.HeaderParamKeyConst;
import com.zmn.uac.business.interfaces.user.UserInfoBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 类描述：拦截器 验证参数头
 *
 * @author xujie
 * @since 2021/06/09 18:10
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    UserInfoBService userInfoBusinessService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(HeaderParamKeyConst.TOKEN_KEY);
        log.info("token 拦截 .........................................");
        // 根据token获取用户id
        ResponseDTO<Long> responseDTO = userInfoBusinessService.getUserIdByToken(token);
        if (responseDTO.isSuccess()) {
            request.setAttribute(HeaderParamKeyConst.USER_ID, responseDTO.getData());
            return true;
        } else {
            responseJson(response, JSON.toJSONString(ResponseDTO.fail(responseDTO.getMessage())));
            return false;
        }
    }

    private void responseJson(HttpServletResponse response, String json) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (IOException e) {
            log.error("response error", e);
        }
    }
}
